<template>
  <div>
    <el-upload :http-request="customUpload" list-type="picture-card" :file-list="fileList" :before-upload="beforeUpload"
      :on-remove="handleRemove" :on-success="handleUploadSuccess" :on-preview="handlePreview" :limit="maxCount"
      accept=".jpeg,.jpg,.gif,.png" :on-exceed="handleExceed">
      <i class="el-icon-plus"></i>
    </el-upload>
    <el-dialog v-if="dialogVisible" :visible.sync="dialogVisible">
      <img width="100%" :src="dialogImageUrl" alt="" />
    </el-dialog>
  </div>
</template>

<script>
import axios from "axios";
import { policy} from "@/api/policy.js";import { getUUID } from "@/utils";
export default {
  name: "multiUpload",
  props: {
    value: Array,
    maxCount: {
      type: Number,
      default: 30
    },
  },
  computed: {
    fileList() {
      let fileList = [];
      for (let i = 0; i < this.value.length; i++) {
        fileList.push({ url: this.value[i] });
      }
      console.log("fileList", fileList);
      return fileList;
    }
  },
  data() {
    return {
      uploadUrl: "", // 替换为你的minio服务器地址
      dialogImageUrl: null,
      dialogVisible: false,
      fileUrl: "",
    };
  },
  methods: {
    emitInput(fileList) {
      this.$emit("input", fileList.map(file => file.url));
      // let value = [];
      // for (let i = 0; i < fileList.length; i++) {
      //   value.push(fileList[i]);
      // }
      // this.$emit("input", value);
    },
    // emitInput(fileList) {
    //   this.$emit("input", fileList.map(file => file.url));
    // },
    handleRemove(file, fileList) {
      this.emitInput(fileList);
    },
    handlePreview(file) {
      this.dialogImageUrl = file.url;
      this.dialogVisible = true;
    },
    customUpload(option) {
    },
    beforeUpload(file) {
      const _self = this;
      const bucketName = 'images'; // bucket名称
      const fileName = getUUID() + file.name.split('.').pop(); // 使用getUUID生成唯一标识符

      return policy({ bucketName, fileName }).then(response => {
        if (response.code === 0) {
          this.fileUrl = response.data.split('?')[0];
          // console.log(file.url);
          // _self.value.push(file.url);

          const uploadUrl = response.data;
          // 设置axios的headers
          const config = {
            headers: {
              'Content-Type': file.type,
            }
          };
          // 使用axios发送PUT请求上传文件
          axios.put(uploadUrl, file, config)
            .then(() => {
              this.handleUploadSuccess(response, file);
              _self.$message.success('文件上传成功');
            })
            .catch(error => {
              _self.$message.error('文件上传失败');
              throw error; // 重新抛出错误以供调用者处理
            });
          return true;
        } else {
          _self.$message.error('获取上传签名失败');
          return false;
        }
      }).catch(error => {
        console.error("Error getting policy from server: ", error);
        _self.$message.error('获取上传签名失败');
        return false;
      });
    },
    handleUploadSuccess(res, file) {
      this.fileList.push({
        name: file.name,
        // url: this.dataObj.host + "/" + this.dataObj.dir + "/" + file.name； 替换${filename}为真正的文件名
        url: this.fileUrl
      });
      this.emitInput(this.fileList);
    },
    handleExceed(files, fileList) {
      this.$message({
        message: "最多只能上传" + this.maxCount + "张图片",
        type: "warning",
        duration: 1000
      });
    }
  }
}
//     beforeUpload(file) {
//       const _self = this;
//       const fileName = file.name;
//       const bucketName = "images";
//       return policy({ fileName,bucketName }).then(response => {
//         _self.dataObj = {
//           policy: response.data.policy,
//           signature: response.data.signature,
//           key: response.data.key, // 这里应该是minio期望的文件存储路径
//           ossaccessKeyId: response.data.accessid
//         };
//         _self.headers = {
//           "Content-Type": file.type,
//           "Authorization": _self.dataObj.signature
//         };
//         return true;
//       }).catch(err => {
//         console.error("Error getting policy from server: ", err);
//         return false;
//       });
//     },
//     handleUploadSuccess(res, file) {
//       // 这里可以处理上传成功后的逻辑，例如更新fileList
//       this.fileList.push({ name: file.name, url: this.dataObj.host + "/" + this.dataObj.key });
//       this.emitInput(this.fileList);
//     },
//     handleExceed(files, fileList) {
//       this.$message.warning(`最多只能上传${this.maxCount}张图片`);
//     }
//   }
// };
</script>

<style scoped>
/* Your CSS styles */
</style>
